package com.wuyou.mybatishandlerdemo.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Intercepts({
        @Signature(type = Executor.class, method = "update",
                args = {MappedStatement.class, Object.class})
})
@Component
public class AutoFillInterceptor implements Interceptor {

//    @Autowired
//    private UserContext userContext;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];

        // 只处理插入和更新操作
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        if (sqlCommandType == SqlCommandType.INSERT || sqlCommandType == SqlCommandType.UPDATE) {
            autoFillFields(parameter, sqlCommandType);
        }

        return invocation.proceed();
    }

    private void autoFillFields(Object parameter, SqlCommandType commandType) {
        if (parameter == null) return;

        MetaObject metaObject = SystemMetaObject.forObject(parameter);
//        String currentUserId = userContext.getCurrentUserId();
        String currentUserId = "1";
        Date now = new Date();

        if (commandType == SqlCommandType.INSERT) {
            if (metaObject.hasGetter("createTime")) {
                metaObject.setValue("createTime", now);
            }
            if (metaObject.hasGetter("createBy")) {
                metaObject.setValue("createBy", currentUserId);
            }
        }

        if (metaObject.hasGetter("updateTime")) {
            metaObject.setValue("updateTime", now);
        }
        if (metaObject.hasGetter("updateBy")) {
            metaObject.setValue("updateBy", currentUserId);
        }
    }
}
